package middleware

import (
	"cms/store"
	"fmt"
	"github.com/gin-gonic/gin"
	"strings"
)

func AuthMiddleware(ctx *gin.Context) {
	tok := ctx.GetHeader("Authorization")
	if tok == "" {
		ctx.AbortWithStatusJSON(401, gin.H{
			"success": false,
			"message": "token为空",
		})
		return
	}
	defer func() {
		if err := recover(); err != nil {
			ctx.AbortWithStatusJSON(401, gin.H{
				"success": false,
				"message": fmt.Sprintf("%s", err),
			})
		}
	}()
	temps := strings.Split(tok, " ")
	user, err := store.GetAdminToken(temps[1])
	if err != nil {
		ctx.AbortWithStatusJSON(401, gin.H{
			"success": false,
			"message": fmt.Sprintf("%s", err),
		})
		return 
	}
	ctx.Set("admin_token", temps[1])
	ctx.Set("admin_user", user)
	ctx.Next()
}
